package cn.tradewin.advisor.persist.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.advisor.persist.mapper.CodetableMapper;
import cn.tradewin.advisor.persist.model.CodeLabel;
import cn.tradewin.advisor.persist.model.Codetable;
import cn.tradewin.advisor.persist.model.CodetableExample;
import cn.tradewin.advisor.persist.model.CodetableKey;
import cn.tradewin.advisor.persist.services.CodetableService;

public class CodetableServiceImpl implements CodetableService {

	private final SqlSessionFactory sqlSessionFactory;
	
	public CodetableServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	@Override
	public int addCategory(Codetable codetable) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CodetableMapper mapper = session.getMapper(CodetableMapper.class);
			int iCount = mapper.insert(codetable);
			if (iCount < 0) {
				session.rollback();
				return iCount;
			}
			session.commit();
			return  iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<Codetable> listAllCodetable() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CodetableMapper mapper = session.getMapper(CodetableMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<Codetable> listAllCodetableByCategory(String category,
			String lang) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CodetableMapper mapper = session.getMapper(CodetableMapper.class);
			CodetableExample example = new CodetableExample();
			example.createCriteria().andCategoryEqualTo(category);
			example.createCriteria().andLangEqualTo(lang);
			return mapper.selectByExample(example);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<CodeLabel> listCategory(String category, String lang) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CodetableMapper mapper = session.getMapper(CodetableMapper.class);
			CodetableKey param = new CodetableKey();
			param.setCategory(category);
			param.setLang(lang);
			return mapper.selectCategory(param);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}
